<template>
  <div class="tab_nav_bg" >
    <div  class="flex_center">
      <van-icon name="arrow-left" class="nav_left_icon" @click="$router.go(-1)"  size="18px"/>
      <div style="flex: 1;text-align: center">{{$route.query.payChannel + ' '+ $t('还款')}}</div>
    </div>
  </div>
  <div class="wrapper">
    <div class="card">
      <div style="padding-bottom: 15px;font-size: 20px">{{ $t('剩余应还金额') }}</div>
      <div @click="editAmountShow = true">
         <span class="card_amount">
        <span>₱{{ repaymentInfo.payAmount }}</span>
      </span>
        <img src="../../../assets/order/edit.png">
      </div>
    </div>
    <div style="padding: 10px 0;text-align: center;background-color: #FFFFFF;margin-top: 15px">
      <img v-if="qrCodeImgStr" :src="qrCodeImgStr" class="qrCode_img" style="width: 300px;height: 500px">
      <div v-else style="height: 100px;line-height: 100px">
        <van-button type="primary" @click="createVirtualCard">{{ $t('重新获取') }}</van-button>
      </div>
      <div v-show="qrCodeValidTime"  style="font-size: 16px;color:#FC752B;padding: 15px 15px 0px 15px">This QR code is valid for {{qrCodeValidTime}}. Please take a screenshot and save it</div>

      <qrcode-vue style="display: none" id="qrCode_img" :size="250"
                  :value="repaymentInfo.h5Link"></qrcode-vue>

    </div>
    <div style="margin: 20px 0;text-align: center">
      <!--      <van-button style="width: 100%;" @click="saveQrCode" type="primary">{{ $t('保存到手机') }}-->
      <!--      </van-button>-->
    </div>
    <div class="qrCode_card">
      <div style="text-align: center;padding-bottom: 20px">
        <h3 style="padding: 0 15px;text-align: left">Repayment Guidelines</h3>
      </div>
      <div class="steps_item" v-for="item in repayChannelInfo.guideUrlList" :key="item">
        <img class="step_content_img" :src="item">
      </div>
    </div>

  </div>

  <van-dialog v-model:show="editAmountShow" :title="$t('编辑还款金额')" @confirm="editAmountConfirm"
              show-cancel-button>
    <div style="padding: 20px 0">
      <van-field style="font-size: 20px" v-model="repayAmount" type="digit"
                 :placeholder="$t('请输入还款金额')"></van-field>
    </div>
  </van-dialog>
</template>

<script>
import {nextTick, onMounted, ref} from "vue";
import {useStore} from "vuex";
import {Dialog, Toast} from "vant";
import {fetchRepaymentType, fetchVirtualCard, virtualCardByRegister} from "@/api/order";
import {useRoute} from "vue-router";
import QrcodeVue from "qrcode.vue";
import {dataURLtoFile} from "@/utils/tool";
import {useI18n} from 'vue-i18n'

export default {
  components: {
    QrcodeVue,
    [Dialog.Component.name]: Dialog.Component,
  },
  setup() {
    const store = useStore()
    const editAmountShow = ref(false)
    const repayAmount = ref(null)
    const {payType, payChannel, loanRecordId, channelType, amount: payAmount} = useRoute().query
    const repayChannelInfo = ref({})
    const repaymentInfo = ref({})
    const qrCodeImgStr = ref(null)
    const qrCodeValidTime = ref(null)
    const {t} = useI18n()
    const logo_config = {
      'YEECOPAY': {
        url: require('../../../assets/order/yeeco_qrlogo.png'),
        color: '#9bc023'
      },
      'SKYPAY': {
        url: require('../../../assets/order/skypay_qrlogo.png'),
        color: '#0068b7'
      },
      'PAYSO': {
        url: require('../../../assets/order/payso_qrlogo.jpg'),
        color: '#38168d'
      },
    }

    async function editAmountConfirm() {
      Toast.loading({
        message: t('加载中'),
        forbidClick: true,
        duration: 0
      });
      const amount = parseInt(repayAmount.value)
      if (!amount) {
        Toast(t('请输入还款金额'))
      }
      if (amount <= 10) {
        Toast(t('还款金额过低!'))
      }
      await createVirtualCard()
    }

    async function createVirtualCard() {
      const amount = parseInt(repayAmount.value || payAmount)
      const params = {
        payType: payType,
        channelName: payChannel,
        payAmount: amount || payAmount,
        loanRecordId,
        channelType,
      }
      const res = await virtualCardByRegister(params)
      if (res.code === 1) {
        getData()
      }
    }

    async function fetchCardPay() {
      const res = await fetchVirtualCard({loanRecordId})
      if (res.code === 1 && res.data) {
        repaymentInfo.value = {...res.data,}
      } else {
        repaymentInfo.value = {}
      }

    }

    function canvas_to_img(el) {
      const canvas = document.getElementById(el);
      const base64Str = canvas.toDataURL('image/png');
      return base64Str
    }

    //
    function createImage(imageUrl) {
      return new Promise((resolve) => {
        let image = new Image();
        image.src = imageUrl
        image.width = 100
        image.height = 80
        image.onload = function () {
          resolve(image)
        }
      })
    }

    // 绘制canvas内容
    async function draw_Content() {
      const logo_url = logo_config[repayChannelInfo.value.channelCode].url
      const textColor = logo_config[repayChannelInfo.value.channelCode].color
      const APP_NAME = localStorage.getItem('appName')
      let canvas = document.createElement('canvas');
      canvas.height = 500
      canvas.width = 300
      let base64Str = canvas_to_img('qrCode_img')
      let qrCodeImg = await createImage(base64Str)
      let logoImg = await createImage(logo_url)
      const imgX = ((canvas.width - logoImg.width) / 2);
      let ctx = canvas.getContext('2d');
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.fillStyle = "#ffffff"
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(qrCodeImg, 25, 125, 250, 250);
      ctx.drawImage(logoImg, imgX, 30, logoImg.width, logoImg.height);
      draw_text(ctx, '₱' + repaymentInfo.value.payAmount, {
        x: 150, y: 460
      }, {
        fontSize: '30px',
        color: textColor
      })
      draw_text(ctx, APP_NAME, {
        x: 150, y: 410
      }, {
        fontSize: '30px',
        color: textColor
      })
      qrCodeImgStr.value = canvas.toDataURL('image/png')
    }

    // 绘制文本
    function draw_text(ctx, text_value, position, option = {}) {
      let gradient = ctx.createLinearGradient(0, 0, 600, 400);
      gradient.addColorStop(0, option.color || 'red');
      ctx.fillStyle = gradient;
      let text = text_value
      ctx.font = option.fontSize + ' Consolas'
      ctx.textAlign = "center"
      ctx.textBaseline = "middle"
      ctx.fillText(text, position.x, position.y)
      ctx.fillStyle = 'black'
      ctx.fill()
    }

    async function getRepayment() {
      const res = await fetchRepaymentType({
        productName: localStorage.getItem('productName')
      })
      if (res.code === 1) {
        repayChannelInfo.value = res.data.find(item => item.channelCode === payChannel && item.channelType === channelType) || {}
      }
      // 清除loading
      store.dispatch('changeLoading', false)
    }

    async function getData() {
      Toast.loading({
        message: t('加载中'),
        forbidClick: true,
        duration: 0
      });
      const p1 = getRepayment()
      const p2 = fetchCardPay()
      Promise.all([p1, p2]).then(res => {
        Toast.clear()
        if (repaymentInfo.value.h5Link) {
          draw_Content()
          if (channelType === 'YEECOPAY'){
            qrCodeValidTime.value = '30 minutes'
          } else {
            qrCodeValidTime.value = '24 hours'
          }
        } else {
          repaymentInfo.value = {}
          repayAmount.value = null
          qrCodeValidTime.value = null
          qrCodeImgStr.value = ""
          Toast.fail('Error: Please retrieve again')

        }
        // 清除loading
        store.dispatch('changeLoading', false)
      })
    }

    onMounted(() => {
      getData()
    })
    return {
      qrCodeImgStr,
      repayAmount,
      editAmountShow,
      createVirtualCard,
      editAmountConfirm,
      repayChannelInfo,
      repaymentInfo,
      qrCodeValidTime
    }
  }
}
</script>

<style lang="less" scoped>
.wrapper {
  padding: 15px;
  margin-top: -150px;
  .card {
    box-sizing: border-box;
    padding: 15px;
    background-color: #FFFFFF;
    border-radius: 10px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
    margin-bottom: 15px;

    .card_amount {
      color: #FFC74C;
      font-size: 40px;
      border-bottom: 2px solid #FC752B;
      margin-right: 5px;
      padding-right: 10px;
    }

    .card_item {
      padding: 8px 15px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
    }
  }

  .step_title {
    background-color: #FFC09C;
    padding: 10px;
    box-sizing: border-box;
    width: 200px;
    border-radius: 0 20px 20px 0;

  }

  .steps_item {
    background-color: #FFFBED;
    padding: 10px;
    margin: 20px 20px 0 20px;
    box-sizing: border-box;
    text-align: center;
    border-radius: 6px;

    .step_content_img {
      height: 400px;
      width: 300px;
    }
  }

  .qrCode_img {
    box-sizing: border-box;
    border: 1px solid #e6e3e3;
    border-radius: 6px;
  }

  .qrCode_card {
    margin-top: 20px;
    background-color: #ffffff;
    font-size: 16px;
    border-radius: 6px;
    padding-top: 10px;


    .step_img {
      background-image: url("../../../assets/order/step_img.png");
      height: 36px;
      width: 97px;
      background-size: 100% 100%;
      text-align: center;
      color: #99503D;
      line-height: 36px;
      margin-bottom: 15px;

    }

    .step_tips {
      text-align: left;
      font-size: 12px;
      margin: 25px 0;
      padding: 0 20px;
    }
  }
}
</style>